<template>
  <div id="info">
    <el-card style="width: 80%; margin: 0 auto">
      <el-row :gutter="2">
        <el-col :span="6">
          <el-avatar
            :alt="'无'"
            :shape="'square'"
            :size="200"
            :src="userDetail?.avatar"
            lazy
          />
        </el-col>
        <el-col :span="18">
          <el-descriptions
            :column="2"
            :label-width="150"
            border
            size="large"
            title="个人信息"
          >
            <template #extra>
              <el-button type="primary" @click="openUpdateModel"
                >修改个人信息
              </el-button>
              <el-button type="danger" @click="openUpdatePwd"
                >修改密码
              </el-button>
            </template>
            <el-descriptions-item align="center" label="账号">
              <el-text>{{ userDetail?.username }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="昵称">
              <el-text>{{ userDetail?.nickname }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="邮箱">
              <el-text>{{ userDetail?.email || "无" }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="电话">
              <el-text>{{ userDetail?.phone || "无" }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="创建时间">
              <el-text>{{ userDetail?.createTime }}</el-text>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-card>
    <el-card style="width: 80%; margin: 10px auto">
      <el-tabs
        v-model="activeName"
        class="demo-tabs"
        @tab-change="handleTabClick"
      >
        <el-tab-pane label="登录日志" name="loginLog">
          <el-scrollbar :max-height="500">
            <el-card
              v-for="item in loginLogList"
              :key="item.id"
              shadow="hover"
              style="margin: 10px; padding: 10px"
            >
              <el-descriptions :label-width="150">
                <el-descriptions-item label="登录方式：">
                  {{ getLoginMethodMsg(item.loginMethod) }}
                </el-descriptions-item>
                <el-descriptions-item label="登录状态：">
                  <el-tag :type="item.status ? 'success' : 'danger'"
                    >登录{{ item.status ? "成功" : "失败" }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="登录时间："
                  >{{ item.createTime }}
                </el-descriptions-item>
                <el-descriptions-item label="登录IP："
                  >{{ item.loginIp }}
                </el-descriptions-item>
                <el-descriptions-item label="IP来源："
                  >{{ item.ipRegion }}
                </el-descriptions-item>
                <el-descriptions-item label="操作系统：">
                  {{ item.os }}
                </el-descriptions-item>
                <el-descriptions-item label="浏览器：">
                  {{ item.browser }}
                </el-descriptions-item>

                <el-descriptions-item label="错误信息：">
                  {{ item.errorMsg || "无" }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-scrollbar>
        </el-tab-pane>
        <el-tab-pane label="收货地址管理" name="address">
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            @click="openAddressModel"
            >新增地址
          </el-button>
          <el-scrollbar :max-height="500">
            <el-card
              v-for="(item, index) in addressList"
              :key="item.id"
              shadow="hover"
              style="margin: 10px"
            >
              <div>
                <el-space>
                  <el-text size="large">{{ item?.contact }}</el-text>
                  <el-text size="large">{{ item?.phone }}</el-text>
                  <el-text size="large">{{ item?.areaAddress }}</el-text>
                  <el-text size="large">{{ item?.detailAddress }}</el-text>
                </el-space>
              </div>
              <div style="border: solid 1px #f5f5f5; margin: 5px 0">
                <div style="float: left">
                  <el-checkbox
                    :false-value="0"
                    :model-value="item?.firstStatus"
                    :true-value="1"
                    @click="handleAddressStatusChange(item)"
                    >{{ item?.firstStatus ? "已设为默认地址" : "设为默认地址" }}
                  </el-checkbox>
                </div>
                <div style="float: right; margin: 5px 0">
                  <el-button
                    :disabled="index === 0"
                    size="small"
                    @click="addressUpChange(index)"
                    >上移
                  </el-button>
                  <el-button
                    :disabled="index === 0 || index === addressList.length - 1"
                    size="small"
                    @click="addressUpChange(index, false)"
                    >下移
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="openAddressModel(item)"
                    >修改
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteAddress(item.id)"
                    >删除
                  </el-button>
                </div>
              </div>
              <el-row>
                <el-col :span="18" />
                <el-col :span="4" />
              </el-row>
            </el-card>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改信息弹窗-->
    <el-dialog
      v-model="updateVisible"
      center
      destroy-on-close
      title="修改个人信息"
      width="35%"
      @close="handleClose(true)"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="updateFormRef"
          :model="updateInfo"
          :rules="rules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-scrollbar :max-height="400" style="width: 100%">
              <el-col>
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    v-model="updateInfo.nickname"
                    clearable
                    placeholder="请输入昵称"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="updateInfo.sex">
                    <el-radio :value="0" label="女" />
                    <el-radio :value="1" label="男" />
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="电话" prop="phone">
                  <el-input
                    v-model="updateInfo.phone"
                    clearable
                    placeholder="请输入电话号码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="邮箱" prop="email">
                  <el-input
                    v-model="updateInfo.email"
                    clearable
                    placeholder="请输入邮箱"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="头像" prop="avatar">
                  <upload-image
                    :urls="[updateInfo.avatar]"
                    limit="1"
                    @update:url="handleAvatar"
                  />
                </el-form-item>
              </el-col>
            </el-scrollbar>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="handleUpdateInfoSubmit"
            >确 定
          </el-button>
          <el-button @click="handleClose(true)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改密码弹窗-->
    <el-dialog
      v-model="updatePwdVisible"
      center
      destroy-on-close
      title="修改密码"
      width="35%"
      @close="handleClose"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="updatePwdRef"
          :model="updatePwdData"
          :rules="pwdRules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-scrollbar :max-height="400" style="width: 100%">
              <el-col>
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input
                    v-model="updatePwdData.oldPassword"
                    clearable
                    placeholder="请输入旧密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="updatePwdData.newPassword"
                    clearable
                    placeholder="请输入新的密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="updatePwdData.confirmPassword"
                    clearable
                    placeholder="请再次输入新的密码"
                    show-password
                    type="password"
                  />
                </el-form-item>
              </el-col>
            </el-scrollbar>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="updatePwdSubmit">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增地址弹窗-->
    <el-dialog
      v-model="addressVisible"
      center
      destroy-on-close
      title="新增地址"
      width="35%"
      @close="handleAddressClose"
    >
      <!-- 滚动 -->
      <el-scrollbar max-height="60vh">
        <!-- 表单 -->
        <el-form
          ref="addressRef"
          :model="address"
          :rules="addressRules"
          label-width="auto"
          style="padding: 10px"
        >
          <el-row :gutter="20">
            <el-scrollbar :max-height="400" style="width: 100%">
              <el-col>
                <el-form-item label="联系人" prop="contact">
                  <el-input
                    v-model="address.contact"
                    clearable
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="电话号码" prop="phone">
                  <el-input
                    v-model="address.phone"
                    clearable
                    placeholder="请输入电话号码"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="区域地址" prop="areaAddress">
                  <el-cascader
                    v-model="tmpPlace"
                    :options="addressData"
                    :props="{
                      label: 'name',
                      value: 'name',
                    }"
                    class="full"
                    clearable
                    @change="handleChange"
                  />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="详细地址" prop="detailAddress">
                  <el-input
                    v-model="address.detailAddress"
                    clearable
                    placeholder="请输入详细地址"
                  />
                </el-form-item>
              </el-col>
            </el-scrollbar>
          </el-row>
        </el-form>
      </el-scrollbar>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="handleAddressSubmit"
            >确 定
          </el-button>
          <el-button @click="handleAddressClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { useUserStore } from "@/store";

import {
  AddressControllerService,
  AddressInsertDTO,
  AddressUpdateDTO,
  AddressVO,
  LoginLogControllerService,
  LoginLogVO,
  UpdatePasswordDTO,
  UserInfoControllerService,
  UserInfoUpdateDTO,
  UserInfoVO,
} from "@/api";
import { nextTick, ref } from "vue";
import UploadImage from "@/components/UploadImage.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { addressData } from "@/assets/data/address";

const userStore = useUserStore();
const user = userStore.userInfo;
const userDetail = ref<UserInfoVO>();

//根据用户Id获取用户信息
function getUserDetailInfo() {
  UserInfoControllerService.getUserDetailInfoUsingGet(user.id as number).then(
    (res) => {
      userDetail.value = res.data;
    }
  );
}

//修改用户信息
const updateVisible = ref(false);
const updateFormRef = ref();
const updateInfo = ref<UserInfoUpdateDTO>({});

// 规则
const rules = {
  email: [
    {
      type: "email",
      message: "邮箱格式不正确",
      trigger: "blur",
    },
  ],
  phone: [
    {
      len: 11,
      message: "手机号码长度不正确",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
};

//修改用户弹窗
function openUpdateModel() {
  updateInfo.value = {
    id: userDetail.value?.id,
    sex: userDetail.value?.sex,
    nickname: userDetail.value?.nickname,
    phone: userDetail.value?.phone || "",
    email: userDetail.value?.email || "",
    avatar: userDetail.value?.avatar || "",
  };
  updateVisible.value = true;
}

//更改用户头像
function handleAvatar(urls: string[]) {
  updateInfo.value!.avatar = urls[0];
}

const closeFlag = ref(false);

//关闭弹窗事件
function handleClose(infoFlag?: boolean) {
  if (closeFlag.value) {
    closeFlag.value = false;
    return;
  }
  ElMessageBox.confirm(
    `确定要关闭修改个人${infoFlag === true ? "信息" : "密码"}弹窗吗？`
  )
    .then(() => {
      if (infoFlag === true) updateVisible.value = false;
      else updatePwdVisible.value = false;
      closeFlag.value = true;
    })
    .catch(() => {
      ElMessage.info("取消了关闭弹窗");
    });
}

//修改信息提交
function handleUpdateInfoSubmit() {
  updateFormRef.value.validate((validate: boolean) => {
    if (validate) {
      UserInfoControllerService.updateUserInfoUsingPut(updateInfo.value).then(
        (res) => {
          //提醒
          ElMessage.success(res.data);
          //关闭弹窗
          updateVisible.value = false;
          //刷新数据
          getUserDetailInfo();
        }
      );
    }
  });
}

const updatePwdData = ref<UpdatePasswordDTO>({});
const updatePwdVisible = ref(false);
const updatePwdRef = ref();

//二次密码确认校验
function validatePwd(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
    return;
  }
  if (value !== updatePwdData.value.newPassword) {
    callback(new Error("两次密码不一致"));
    return;
  }
  callback();
}

//规则
const pwdRules = {
  oldPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请输入旧的密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  newPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请输入新的密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      trigger: "blur",
      message: "请再次输入密码",
    },
    {
      min: 8,
      message: "密码不能小于8位",
      trigger: "blur",
    },
    { validator: validatePwd, trigger: "blur" },
  ],
};

//打开确认密码弹窗
function openUpdatePwd() {
  //设置用户ID
  updatePwdData.value.id = userDetail.value?.id;
  // 打开弹窗
  updatePwdVisible.value = true;
}

const router = useRouter();
const route = useRoute();

// 修改密码提交
function updatePwdSubmit() {
  updatePwdRef.value.validate((validate: boolean) => {
    if (validate) {
      UserInfoControllerService.updateUserInfoSelfPwdUsingPut(
        updatePwdData.value
      ).then((res) => {
        ElMessage.success(res.data);
        //退出登录
        userStore.logout();
        //获取路径参数
        const params = new URLSearchParams(
          route.query as Record<string, string>
        ).toString();
        //拼接重定向路径
        const redirect = params ? `${route.path}?${params}` : route.path;
        router.push(`/basic/login?redirect=${encodeURIComponent(redirect)}`);
      });
    }
  });
}

getUserDetailInfo();
const activeName = ref("loginLog");
if (route.query.tab) {
  activeName.value = route.query.tab as string;
}

const initFlag = ref(0);
const handleTabClick = () => {
  console.log(activeName.value);
  if (activeName.value === "address" && initFlag.value === 0) {
    // 首次点击地址，查询地址信息
    getAddress();
  }
};

//获取登录日志信息
const loginLogList = ref<LoginLogVO[]>([]);

function getLoginLogList() {
  LoginLogControllerService.getLoginLogByKeywordUsingGet().then((res) => {
    loginLogList.value = res.data || [];
  });
}

//  获取登录方式
function getLoginMethodMsg(value: number) {
  if (value === 0) {
    return "账号登录";
  }
  if (value === 1) {
    return "邮箱登录";
  }
  if (value === 2) {
    return "手机号登录";
  }
  return "未知";
}

getLoginLogList();
//添加地址
const addressRules = {
  areaAddress: [
    {
      required: true,
      message: "请选择区域地址",
      trigger: "blur",
    },
  ],
  contact: [
    {
      required: true,
      message: "请输入联系人",
      trigger: "blur",
    },
  ],
  detailAddress: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入联系人号码",
      trigger: "blur",
    },
    {
      len: 11,
      message: "手机号码长度不正确",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确",
      trigger: "blur",
    },
  ],
};
const addressList = ref<AddressVO[]>([]);

//获取地址信息
function getAddress() {
  AddressControllerService.getAddressListUsingGet().then((res) => {
    addressList.value = res.data || [];
  });
}

// 新增地址
const address = ref<AddressInsertDTO | AddressUpdateDTO>({});
const addressVisible = ref(false);
const addressRef = ref();

//打开新增地址弹窗

const tmpPlace = ref([]); // 临时地址

//地址选项发生改变
const handleChange = (value: any) => {
  if (value) {
    tmpPlace.value = value;
    address.value.areaAddress = value.join(" ");
  }
};

function openAddressModel(data: AddressVO) {
  addressVisible.value = true;
  nextTick(() => {
    if (addressRef.value) {
      addressRef.value.resetFields();
    }
    if (data.id) {
      //拷贝数据
      address.value = { ...data };
      // 设置地址数据
      tmpPlace.value = address.value.areaAddress!.split(" ");
    }
  });
}

// 关闭新增地址弹窗
function handleAddressClose() {
  if (addressRef.value) {
    addressRef.value.resetFields();
  }
  //清除地址
  tmpPlace.value = [];
  addressVisible.value = false;
}

// 提交地址
function handleAddressSubmit() {
  addressRef.value.validate((valid: boolean) => {
    if (valid) {
      (!address.value.id
        ? AddressControllerService.insertAddressUsingPost(address.value)
        : AddressControllerService.updateAddressUsingPut(address.value)
      ).then((res) => {
        // 刷新数据
        ElMessage.success(res.data);
        // 关闭弹窗
        handleAddressClose();
        nextTick(() => {
          // 刷新数据
          getAddress();
        });
      });
    }
  });
}

// 地址首选状态改变
async function handleAddressStatusChange(date: AddressVO) {
  //已经选择，不用再处理
  if (date.firstStatus) return;
  await AddressControllerService.setAddressFirstStaticUsingPut(
    date.id as any
  ).then((res) => {
    ElMessage.success(res.data);
    // 刷新数据
    getAddress();
  });
}

// 地址上下地址改变
async function addressUpChange(index = 1, upFlag = true) {
  //获取两个数据
  const one = addressList.value[index];
  const two = addressList.value[index + (upFlag ? -1 : +1)];
  // 交换一下排序值
  let tmp = one.orderNum;
  one.orderNum = two.orderNum;
  two.orderNum = tmp;
  await AddressControllerService.updateAddressOrderNumUsingPut([
    {
      id: one.id,
      status: one.orderNum,
    },
    {
      id: two.id,
      status: two.orderNum,
    },
  ]).then((res) => {
    ElMessage.success(res.data);
    // 刷新数据
    getAddress();
  });
}

//删除地址
function deleteAddress(id: any) {
  if (addressList.value <= 1) {
    ElMessage.warning("至少保留一个地址信息！");
    return;
  }
  ElMessageBox.confirm("确定要删除该地址？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      AddressControllerService.delAddressUsingDelete([id]).then((res) => {
        ElMessage.success(res.data);
        // 刷新数据
        getAddress();
      });
    })
    .catch(() => {
      return;
    });
}
</script>

<style lang="scss" scoped>
#info {
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
}
</style>
